﻿using System.Diagnostics;
using System.Text;

namespace SeguradoraIA.Framework.Log.DefaultLoggers
{
    public class EventViewerLogger : ILogger
    {
        private readonly string sourceName;

        public bool ListenLogMessage { get; set; }
        public bool ListenLogReturn { get; set; }
        public bool ListenLogSQL { get; set; }
        public bool ListenLogEntry { get; set; }
        public bool ListenLogException { get; set; }


        public EventViewerLogger(string sourceName)
        {
            this.sourceName = sourceName;
        }


        public void Log(LogData logData)
        {
            if (!logData.ShouldLog(ListenLogMessage, ListenLogReturn, ListenLogSQL, ListenLogEntry, ListenLogException))
                return;

            if (!EventLog.SourceExists(sourceName))
                EventLog.CreateEventSource(sourceName, "Application");

            EventLogEntryType entryType = EventLogEntryType.Information;

            if (logData is ExceptionLogData)
                entryType = EventLogEntryType.Error;

            EventLog.WriteEntry(sourceName,GetFomatedMessage(logData), entryType);

        }

        private string GetFomatedMessage(LogData logData)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Thread: ");
            sb.AppendLine(logData.ContextThread.GetHashCode().ToString());

            sb.Append("Data: ");
            sb.AppendLine(logData.CreationDate.ToString("dd/MM/yyyy HH:mm:ss:ffff"));

            sb.Append("Linha: ");
            sb.AppendLine(logData.Line);

            sb.Append("Arquivo: ");
            sb.AppendLine(logData.FileName);

            sb.Append("Metodo: ");
            sb.Append(logData.Method);
            sb.Append(" (");
            sb.Append(logData.ParametersDeclaration);
            sb.AppendLine(")");

            sb.AppendLine(logData.Message);

            sb.AppendLine(logData.Information);
            return sb.ToString();
        }
    }
}